package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.common.ResponseCode;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
//        System.out.println(vo);
        if (vo==null|| Strings.isNullOrEmpty(vo.getUsername())||Strings.isNullOrEmpty(vo.getPassword())
        ||Strings.isNullOrEmpty(vo.getCode())||Strings.isNullOrEmpty(vo.getRkey())){
            //快速淘汰校验码。合理利用redis的内存空间
//            redisTemplate.delete(vo.getRkey());
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        // 校验验证码
        String redisCode = (String) redisTemplate.opsForValue().get(vo.getRkey());
        //比对
        if (redisCode==null||!redisCode.equals(vo.getCode())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //快速淘汰校验码。合理利用redis的内存空间
//        redisTemplate.delete(vo.getRkey());
        //根据用户名判断用户是否存在
        SysUser user = this.userMapper.findByUserName(vo.getUsername());
        if (user==null||!passwordEncoder.matches(vo.getPassword(), user.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        LoginRespVo respVo = new LoginRespVo();
        BeanUtils.copyProperties(user,respVo);
        return R.ok(respVo);
    }

    @Override
    public R<Map> generateCaptcha() {
    //生成4为数字验证码
        String s = RandomStringUtils.randomNumeric(4);
        //获取全局唯一id
        String s1 = String.valueOf(idWorker.nextId());
        //验证码存入redis中，并设置有效期1分钟
        redisTemplate.opsForValue().set(s1,s,120, TimeUnit.SECONDS);
        //组装数据
        HashMap<String,String> map = new HashMap<>();
        map.put("rkey",s1);
        map.put("code",s);
        return R.ok(map);
    }
}
